//全排列 II
//测试链接：https://leetcode.cn/problems/permutations-ii/description/
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class PermuteUnique {
    List<List<Integer>> ans;
    List<Integer> path;
    boolean[] check;
    public List<List<Integer>> permuteUnique(int[] nums) {
        ans = new ArrayList<>();
        path = new ArrayList<>();
        check = new boolean[nums.length];

        Arrays.sort(nums);
        dfs(nums,0);
        return ans;
    }

    public void dfs(int[] nums, int pos) {
        if(pos == nums.length) {
            ans.add(new ArrayList<>(path));
        }

        for(int i = 0; i < nums.length; i++) {
            if(check[i] == true ||
                    (i != 0 && check[i-1] == false && nums[i-1] == nums[i]) ) { //判断剪枝
                continue;
            }
            check[i] = true;
            path.add(nums[i]);

            dfs(nums, pos+1);

            path.remove(path.size()-1); //恢复现场
            check[i] = false;
        }

    }
}
